package com.wy.filter;

import com.alibaba.fastjson.JSON;
import com.wy.common.BaseContext;
import com.wy.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路劲匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER= new  AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取拦截路径
        String requestURI = request.getRequestURI();
        //2.定义不被拦截的请求路劲,一般是静态页面
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //3.判断本次请求是否需要处理
        boolean check = check(urls,requestURI);
        //4.不需要处理,直接放行
        if(check){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //5.要处理,判断是否登录,已登录,直接放行(Pc端)
        if (request.getSession().getAttribute("employee") != null) {
            //获取线程中的id值,存放在线程中
            Long empId = (Long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return;
        }
        //手机端获取用户信息
        if (request.getSession().getAttribute("user") != null) {
            log.info("前台用户已登录");
            //获取操作人员的id
            Long userId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //6.未登录则返回未登录提示,通过输出流方式向客户端页面响应
        //此处在前端已经设置了对应的拦截器,只需设置信息传递匹配内容,前端接收到后会进行拦截器处理,跳转页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路劲匹配,检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url:urls){
            boolean match = PATH_MATCHER.match(url,requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
